import React,{useState,useEffect} from 'react';
import {useSelector,useDispatch} from 'react-redux';
import {Helmet} from "react-helmet";
import {actions} from "./store";
import styles from './style.css';

//组件
const Home = (props) => {
  const home = useSelector((state) => {
    // console.log('state:', state);
    return {
      name: state.home.name,
      list: state.home.newsList
    };
  });

  const dispatch = useDispatch();


  if (styles._getCss/** ←使用的是isomorphic-style-loader,即服务端渲染时*/) {
    props.staticContext.css.push(styles._getCss());
  }

  useEffect(() => {
    if (home.list.length === 0) {
      dispatch(actions.getHomeList()); // ←这是必要的 因为如果先访问/Login 再访问首页 是没有从服务端产出的数据的 我们需要自己请求
    }
  }, []);

  return (
    <>
      <Helmet>
        <title>这是SSR新闻页面 - 丰富多彩的资讯</title>
        <meta name='description' content='这是SSR新闻页面 - 丰富多彩的资讯'/>
      </Helmet>
      <div className={styles.test}>
        <div>This is {home.name}!</div>
        {
          home.list && home.list.map((item) => (
            <div key={item}>
              {item}
            </div>
          ))
        }
        <button onClick={() => {
          alert('click')
        }}>
          click
        </button>
      </div>
    </>
  );
};

// 负责在服务器端渲染之前,将这个路由需要的数据提前加载好
Home.loadData = (store) => {
  return store.dispatch(actions.getHomeList());
  /* 这里return的实际是下面这个promise:
    return axiosInstance.get('/api/isLogin').then((res)=>{
      // console.log('res:',res)
      dispatch(changeLogin(res.data.data.login))
    });
  * */
};

export default Home;

